/**
 *    Copyright (c) [2022] [中和农信]
 *    rabbit-mq-plus is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 *
 */
package com.cfpamf.athean.rabbit.mq.plus.service.impl;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import com.cfpamf.athean.rabbit.mq.plus.producer.core.RabbitMqPlusProducerResultTemplate;
import com.cfpamf.athean.rabbit.mq.plus.service.RabbitMqPlusProducerService;

import lombok.extern.slf4j.Slf4j;

/**
 * 类RabbitMqPlusProducerResultTemplateServiceImpl.java的实现描述：
 *
 * @author Andy（陈洪桥）2023年02月17 15:40
 */
@Slf4j
@Service("rabbitMqPlusProducerResultTemplate")
public class RabbitMqPlusProducerResultTemplateServiceImpl implements RabbitMqPlusProducerResultTemplate {

    @Resource
    private RabbitMqPlusProducerService rabbitMqPlusProducerService;

    @Resource
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    @SuppressWarnings("deprecation")
    public void init() {
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, failExchange, routingKey) -> {
            // 记录日志，ReturnsCallback：消息(带有路由键routingKey)到达交换机，与交换机的所有绑定键进行匹配，匹配不到触发回调
            log.error("[rabbitMqPlus]消息发送到队列失败，响应码：{}, 失败原因：{}, 交换机: {}, 路由key：{}, 消息: {}", replyCode, replyText,
                failExchange, routingKey, message);
        });
    }

    @Override
    public void akc(String messageId, String eventNo, String eventTypeCode) {
        log.info("[rabbitMqPlus]生产者消息发送akc，messageId {} eventNo {} eventTypeCode {}", messageId, eventNo,
            eventTypeCode);
        rabbitMqPlusProducerService.updateDoneByEventNoAndEventCode(eventNo, eventTypeCode);
    }

    @Override
    public void nack(String messageId, String eventNo, String eventTypeCode, int retryCount) {
        log.info("[rabbitMqPlus]生产者消息发送nack，messageId {} eventNo {} eventTypeCode {}", messageId, eventNo,
            eventTypeCode);
        rabbitMqPlusProducerService.updateFailByEventNoAndEventCode(eventNo, eventTypeCode, retryCount);
    }

    @Override
    public void fail(String messageId, String eventNo, String eventTypeCode, int retryCount) {
        log.info("[rabbitMqPlus]生产者消息发送fail，messageId {} eventNo {} eventTypeCode {}", messageId, eventNo,
            eventTypeCode);
        rabbitMqPlusProducerService.updateFailByEventNoAndEventCode(eventNo, eventTypeCode, retryCount);
    }

}
